<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索区域 -->
      <el-row class="ml10" v-show="showSearch">
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
          <div>
            <el-button @click="formDialogRef.openDialog()" class="ml10" icon="folder-add" type="primary">新增</el-button>
          </div>
          <el-form-item label="咨询号" prop="inquireNumber" style="padding-top:10px">
            <el-input placeholder="请输入咨询号" style="max-width: 180px" v-model="state.queryForm.inquireNumber" />
          </el-form-item>
          <el-form-item label="手机号" prop="cusTel">
            <el-input placeholder="请输入手机号" style="max-width: 180px" v-model="state.queryForm.cusTel" />
          </el-form-item>
          <el-form-item label="选择状态" prop="trStatus">
            <el-select placeholder="请选择状态" v-model="state.queryForm.trStatus">
              <el-option :key="index" :label="item.label" :value="Number(item.value)" v-for="(item, index) in trip_staus"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList" icon="search" type="primary">查询</el-button>
            <el-button @click="resetQuery" icon="refresh-left">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-table :data="state.dataList"
                @selection-change="handleSelectionChange"
                style="width: 100%"
                v-loading="state.loading"
                border
                :cell-style="tableStyle?.cellStyle"
                :header-cell-style="tableStyle?.headerCellStyle"
      >
        <el-table-column align="center" type="selection" width="40" />
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="行程单号" prop="tripNumber" show-overflow-tooltip />
        <el-table-column label="咨询号" prop="inquireNumber" show-overflow-tooltip />
        <el-table-column label="客户姓名" prop="cusName" show-overflow-tooltip />
        <el-table-column label="手机号" prop="cusTel" show-overflow-tooltip />
        <el-table-column label="出行人数" prop="countPerson" show-overflow-tooltip />
        <el-table-column label="出发时间" prop="goTime" show-overflow-tooltip />
        <el-table-column label="计划天数" prop="planDays" show-overflow-tooltip />
        <el-table-column label="出行费用" prop="tripCosts" show-overflow-tooltip />
        <el-table-column label="服务费用" prop="serviceFee" show-overflow-tooltip />
        <el-table-column label="定制师" prop="tailotrId" show-overflow-tooltip />
        <el-table-column label="地陪" prop="guideId" show-overflow-tooltip />
        <el-table-column label="状态" prop="trStatus" show-overflow-tooltip>
          <template #default="scope">
            {{ trip_staus.find(item => Number(item.value) === Number(scope.row.trStatus))?.label || '未知状态' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="tripRemark" show-overflow-tooltip />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <!-- 修改操作按钮 -->
            <el-button
                icon="edit-pen"
                @click="formDialogRef.openDialog(scope.row.tripId, false)"
                text
                type="primary"
            >
              修改
            </el-button>
            <el-button icon="eye" @click="formDialogRef.openDialog(scope.row.tripId, true)" text type="primary" v-if="scope.row.trStatus === 2">详情</el-button>
            <el-button icon="check" @click="formDialogRef.openDialog(scope.row.tripId)" text type="success">提交</el-button>
            <el-button icon="delete" @click="handleDelete(scope.row)" text type="danger">删除</el-button>            <el-button icon="arrow-left" @click="" text type="warning">退回</el-button>
            <el-button icon="check" @click="" text type="success">签约</el-button>
            <el-button icon="map-location" @click="" text type="primary">地陪</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
          @current-change="currentChangeHandle"
          @size-change="sizeChangeHandle"
          v-bind="state.pagination"
      />
    </div>
    <form-dialog @refresh="getDataList()" ref="formDialogRef" />
  </div>
</template>

<script lang="ts" name="trip" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { selectByCondition, deleteTrip } from '/@/api/trip/trip';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { defineAsyncComponent, ref, reactive, onMounted } from 'vue';
import { useDict } from "/@/hooks/dict";


// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const { trip_staus } = useDict('trip_staus');

// 定义变量
const formDialogRef = ref();
const queryRef = ref();
const showSearch = ref(true);
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps & {
  dataList: any[];
  loading: boolean;
  pagination: any;
  queryForm: {
    inquireNum?: string;
    cusTel?: string;
    trStatus?: string;
  };
} = reactive({
  queryForm: {},  // 初始化查询表单
  dataList: [],
  loading: false,
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1
  },
  pageList: selectByCondition,
});

const {
  getDataList: originalGetDataList,
  currentChangeHandle,
  sizeChangeHandle,
  tableStyle
} = useTable(state);

const getDataList = async () => {
  const hasSearchParams = Object.values(state.queryForm).some(v => v);
  if (hasSearchParams) {
    try {
      state.loading = true;
      const params = {
        page: state.pagination.currentPage,
        size: state.pagination.pageSize,
        inquireNumber: state.queryForm.inquireNumber || '',
        cusTel: state.queryForm.cusTel || '',
        trStatus: state.queryForm.trStatus || ''
      };
      const res = await selectByCondition(params);
      state.dataList = res.data.records || [];
      state.pagination.total = res.data.total || 0;
    } catch (error) {
      useMessage().error('查询失败，请重试');
      console.error('查询错误:', error);
    } finally {
      state.loading = false;
    }
  } else {
    await originalGetDataList();
  }
};

const resetQuery = () => {
  state.queryForm = {};
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  getDataList();  // 重置后刷新数据
};

const handleSelectionChange = (objs: { tripId: string }[]) => {
  selectObjs.value = objs.map(({ tripId }) => tripId);
  multiple.value = !objs.length;
};

const handleDelete = async (row) => {
  if (!row || !row.tripId) {
    useMessage().warning('未找到有效的数据ID');
    return;
  }
  try {
    await useMessageBox().confirm(
        `确定要删除行程单 ${row.tripNumber} 吗？此操作不可撤销。`,
        '删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );
    await deleteTrip(row.tripId);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    if (err.name !== 'Cancel') {
      useMessage().error(err.msg || '删除失败，请稍后重试');
    }
  }
};
</script>
